"""
字符串搜索和替换

问题：
    你想在字符串中搜索和匹配指定的文本模式。
解决方案：
    对于简单的字面模式，直接使用 str.replace() 方法即可。
    对于复杂的模式，请使用 re 模块中的 sub() 函数。
    一个替换回调函数的参数是一个 match 对象，也就是 match() 或者 find() 返回的对象。
    使用 group() 方法来提取特定的匹配部分。回调函数最后返回替换字符串。
"""

import re
from calendar import month_abbr


def use_replace():
    context = "life is short, you need python"
    print(context.replace("you need python", "use python"))
    # 输出结果：
    """
    life is short, use python
    """


def use_re():
    context = "Today is 5/21/2018. Tomorrow is 5/22/2018."
    print(re.sub(r"(\d+)/(\d+)/(\d+)", r"\3-\1-\2", context))
    # 输出结果：
    """
    Today is 2018-5-21. Tomorrow is 2018-5-22.
    """


def use_re_compile():
    context = "Today is 5/21/2018. Tomorrow is 5/22/2018."
    date_pat = re.compile(r"(\d+)/(\d+)/(\d+)")
    print(date_pat.sub(r"\3-\1-\2", context))
    print(date_pat.sub(r"\3-\1-\2", "Tomorrow is 5/22/2018."))
    # 输出结果：
    """
    Today is 2018-5-21. Tomorrow is 2018-5-22.
    Tomorrow is 2018-5-22.
    """


def change_date(m):
    mon_name = month_abbr[int(m.group(1))]
    return "{} {} {}".format(m.group(2), mon_name, m.group(3))


def use_callback():
    """
    使用回调的方式
    """

    context = "Today is 5/21/2018. Tomorrow is 5/22/2018."
    date_pat = re.compile(r"(\d+)/(\d+)/(\d+)")
    print(date_pat.sub(change_date, context))
    # 输出结果：
    """
    Today is 21 May 2018. Tomorrow is 22 May 2018.
    """


def use_subn():
    context = "Today is 5/21/2018. Tomorrow is 5/22/2018."
    date_pat = re.compile(r"(\d+)/(\d+)/(\d+)")
    new_context, n = date_pat.subn(r"\3-\1-\2", context)
    print(new_context, n)
    # 输出结果：
    """
    Today is 2018-5-21. Tomorrow is 2018-5-22. 2
    """


if __name__ == '__main__':
    use_replace()
    use_re()
    use_re_compile()
    use_callback()
    use_subn()
